package net.lbh.share;

import java.util.Map;
import java.util.Set;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;

import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.bean.SocializeEntity;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.SocializeClientListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMDataListener;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.utils.OauthHelper;

/**
 * 
 * 第三方平台 账号
 * <p>
 * 第三方登录平台为：新浪微博、腾讯微博、QQ、QQ空间、微信、人人网、豆瓣
 * 
 * @author BaoHong.Li
 * @date 2015-7-23 上午9:58:06
 * @update (date)
 * @version V1.0
 */
public class PlatformAccountAgent {

	private static final String TAG = PlatformAccountAgent.class.getName();

	private static UMSocialService mController = UMServiceFactory
			.getUMSocialService("com.umeng.login");

	private PlatformAccountAgent() {
	}

	private static PlatformAccountAgent instance;

	public static PlatformAccountAgent getInstance() {

		if (null == instance) {

			synchronized (PlatformAccountAgent.class) {

				if (null == instance) {

					instance = new PlatformAccountAgent();
				}
			}
		}

		return instance;

	}

	public void setDebug(boolean debug) {
		L.isDebug = debug;
	}

	/**
	 * 
	 * 配置 qq开放平台参数
	 * 
	 * @param appId
	 * @param appKey
	 * @return boolean
	 * @autour BaoHong.Li
	 * @date 2015-7-17 下午4:19:22
	 * @update (date)
	 */
	public boolean initQQKeys(String appId, String appKey) {
		return ConstantKeys.initQQKeys(appId, appKey);
	}

	/**
	 * 
	 * 配置 微信开放平台参数
	 * 
	 * @param appId
	 * @param appKey
	 * @return boolean
	 * @autour BaoHong.Li
	 * @date 2015-7-17 下午4:20:21
	 * @update (date)
	 */
	public boolean initWxKeys(String appId, String appSecret) {
		return ConstantKeys.initWxKeys(appId, appSecret);
	}

	/**
	 * 
	 * 配置 人人 开放平台 参数
	 * 
	 * @param appkey
	 * @param appSecret
	 * @return boolean
	 * @autour BaoHong.Li
	 * @date 2015-7-23 上午11:50:29
	 * @update (date)
	 */
	public boolean initRRKeys(String appkey, String appSecret) {
		return ConstantKeys.initRRKeys(appkey, appSecret);
	}

	/**
	 * 
	 * 配置 易信 开放平台 参数
	 * 
	 * @param appId
	 * @return boolean
	 * @autour BaoHong.Li
	 * @date 2015-7-23 上午11:53:32
	 * @update (date)
	 */
	public boolean initYxKeys(String appId) {
		return ConstantKeys.initYxKeys(appId);
	}
	
	/**
	 *
	 * 判断是否授权
	* @param context
	* @param platform [ SHARE_MEDIA ]
	* @return boolean 
	* @throws
	* @autour BaoHong.Li
	* @date 2015-8-6 上午10:17:02 
	* @update (date)
	 */
	public boolean isAuthenticated(Context context, SHARE_MEDIA platform){
		return OauthHelper.isAuthenticated(context,platform);
	}
	/**
	 * 
	 * 授权接口
	 * 
	 * @param context
	 * @param platform
	 *            :SHARE_MEDIA
	 * @param listener
	 * @return void
	 * @autour BaoHong.Li
	 * @date 2015-7-23 上午11:16:08
	 * @update (date)
	 */
	public void doOauthVerify(Context context, SHARE_MEDIA platform,
			final OnAuthListener listener) {

		if (mController == null) {
			mController = UMServiceFactory
					.getUMSocialService("com.umeng.login");
		}

		if (!ConstantKeys.verifyInitKeys(platform)) {
			throw new IllegalArgumentException("please init platform keys");
		}

		mController.doOauthVerify(context, platform, new UMAuthListener() {
			@Override
			public void onError(SocializeException e, SHARE_MEDIA platform) {
				L.d(TAG, " --- 授权失败---");
				if (null !=listener) {
					listener.onFail(e, platform);
				}
			}

			@Override
			public void onComplete(Bundle value, SHARE_MEDIA platform) {
				if (value != null && !TextUtils.isEmpty(value.getString("uid"))) {
					L.d(TAG, " --- 授权成功---");
					if (null !=listener) {
						listener.onSuccess(value, platform);
					}
				} else {
					L.d(TAG, " --- 授权发生错误---");
					if (null !=listener) {
						listener.onFail(new SocializeException("授权发生错误!"), platform);
					}
				}
			}

			@Override
			public void onCancel(SHARE_MEDIA platform) {
				L.d(TAG, " --- 授权取消 ---");
				if (null !=listener) {
					listener.onCancel(platform);
				}
			}

			@Override
			public void onStart(SHARE_MEDIA platform) {
				L.d(TAG, " --- 授权开始 ---");
				if (null !=listener) {
					listener.onStart(platform);
				}
			}

		});

	}

	/**
	 * 获取accesstoken及用户资料
	 * 
	 * @param context
	 * @param platform
	 * @param listener
	 *            <i>[ public void onComplete(int status, Map<String, Object><>
	 *            info) { if(status == 200 && info != null){ StringBuilder sb =
	 *            new StringBuilder(); Set<String> keys = info.keySet();
	 *            for(String key : keys){
	 *            sb.append(key+"="+info.get(key).toString()+"\r\n"); }
	 *            Log.d("TestData",sb.toString()); }else{
	 *            Log.d("TestData","发生错误："+status); } } ]</i>
	 * @return void
	 * @autour BaoHong.Li
	 * @date 2015-7-23 上午10:54:49
	 * @update (date)
	 */
	public void requestPlatformInfo(Context context, SHARE_MEDIA platform,
			UMDataListener listener) {

		if (mController == null) {
			mController = UMServiceFactory
					.getUMSocialService("com.umeng.login");
		}

		if (!ConstantKeys.verifyInitKeys(platform)) {
			throw new IllegalArgumentException("please init platform keys");
		}

		mController.getPlatformInfo(context, SHARE_MEDIA.SINA, listener);

	}

	/**
	 * 
	 * 通过第三方平台 登录 ，返回用户信息 常见登录错误码: sina:http://open.weibo.com/wiki/Error_code
	 * <p>
	 * 腾讯微博: <u>http://wiki.open.t.qq.com/index.php/%E8%BF%94%E5%9B%
	 * 9E%E9%94%99%E8%AF%AF%E7%A0%81%E8%AF%B4%E6%98%8E </u>
	 * <p>
	 * QQ:http://wiki.open.qq.com/index.php?title=Android_API%E8%B0%83%E7%94%A8%
	 * E8%AF%B4%E6%98%8E&=45038
	 * <p>
	 * 
	 * @return void
	 * @autour BaoHong.Li
	 * @date 2015-7-23 上午11:18:43
	 * @update (date)
	 */
	public void loginToPlatform(final Context context, SHARE_MEDIA platform,
			final OnLoginToPlatformListener loginListener) {

		doOauthVerify(context, platform, new OnAuthListener() {

			@Override
			public void onStart(SHARE_MEDIA platform) {
				if (null !=loginListener) {
					
					loginListener.onStart(platform);
				}
			}

			@Override
			public void onCancel(SHARE_MEDIA platform) {

				if (null !=loginListener) {
					loginListener.onCancel(platform);
				}
			}

			@Override
			public void onFail(SocializeException e, SHARE_MEDIA platform) {

				if (null !=loginListener) {
					loginListener.onCancel(platform);
					loginListener.onFail(e, platform);
				}
			}

			@Override
			public void onSuccess(Bundle value, final SHARE_MEDIA platform) {

				// 登录成功，获取用户信息
				requestPlatformInfo(context, platform, new UMDataListener() {

					@Override
					public void onStart() {
						L.d(TAG, " --- 获取用户信息开始---");
					}

					@Override
					public void onComplete(int status, Map<String, Object> info) {

						if (status == 200 && info != null) {
							
							StringBuilder sb = new StringBuilder();
							Set<String> keys = info.keySet();
							for (String key : keys) {
								sb.append(key + "=" + info.get(key).toString()
										+ "\r\n");
							}
							L.d(TAG, sb.toString());
							
							L.e(TAG, "--- 获取用户信息成功 ---");
							L.e(TAG, "--- 登录成功 ---");
							if (null !=loginListener) {
								loginListener.onSuccess(status, info);
							}
						} else {
							L.e(TAG, "--- 获取用户信息发生错误! ---");
							if (null !=loginListener) {
								loginListener.onFail(new SocializeException(
										"获取用户信息发生错误!"), platform);
							}
						}
					}

				});
			}
		});

	}

	public void deleteOauth(final Context context, final SHARE_MEDIA platform,
			final OnLoginoutToPlatformListener loginoutListener) {

		mController.deleteOauth(context, platform,
				new SocializeClientListener() {
					@Override
					public void onStart() {

					}

					@Override
					public void onComplete(int status, SocializeEntity entity) {
						if (status == 200) {
							if (null !=loginoutListener) {
								loginoutListener.onSuccess(status, entity);
							}
						} else {
							if (null != loginoutListener) {
								loginoutListener.onFail(new SocializeException(
										"删除授权失败！"), platform);
							}
						}
					}
				});
	}

	/**
	 *
	 * 从第三方平台 注销登录
	* @param context
	* @param platform
	* @param loginoutListener
	* @return void
	* @autour BaoHong.Li
	* @date 2015-7-23 下午1:05:05 
	* @update (date)
	 */
	public void loginoutToPlatform(final Context context,
			final SHARE_MEDIA platform,
			final OnLoginoutToPlatformListener loginoutListener) {
		deleteOauth(context, platform, loginoutListener);
	}

	/**
	 * 
	 * 接收 回调
	 * 
	 * @param requestCode
	 * @param resultCode
	 * @param data
	 * @return void
	 * @throws
	 * @autour BaoHong.Li
	 * @date 2015-7-23 上午10:09:51
	 * @update (date)
	 */
	public void onActivityResult(int requestCode, int resultCode, Intent data) {

		/** 使用SSO授权必须添加如下代码 */
		UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(
				requestCode);
		if (ssoHandler != null) {
			ssoHandler.authorizeCallBack(requestCode, resultCode, data);
			L.d(TAG, "#### ssoHandler.authorizeCallBack");
		}

	}
}
